package rotateArray.javaCode;

import java.util.Arrays;

public class rotateArray {

    /**
     * 暴力解法
     * @param nums
     * @param k
     */
    public static void rotate1(int[] nums, int k) {
        if (nums.length == 1) {
            return;
        }
        if (k > nums.length) {
            k = k % nums.length;
        }
        int[] temp = new int[k];
        int[] temp2 = new int[nums.length];
        int index = 0;
        for (int i = nums.length - k; i < nums.length; i++) {
            temp[index] = nums[i];
            index++;
        }
        for (int i = 0; i < nums.length; i++) {
            if (i < k) {
                temp2[i] = temp[i];
            } else {
                temp2[i] = nums[i-k];
            }
        }
        for (int i = 0; i < nums.length; i++) {
            nums[i] = temp2[i];
        }
    }

    /**
     * 进阶解法
     * @param nums
     * @param k
     */
    public static void rotate2(int[] nums, int k) {
        int n = nums.length;
        int[] newArr = new int[n];
        for (int i = 0; i < n; ++i) {
            newArr[(i + k) % n] = nums[i];
        }
        System.arraycopy(newArr, 0, nums, 0, n);
    }

    /**
     * 翻转解法
     * @param nums
     * @param k
     */
    public static void rotate(int[] nums, int k) {
        k %= nums.length;
        // 整体数组翻转
        reverse(nums, 0, nums.length - 1);
        // 数组前部分翻转
        reverse(nums, 0, k - 1);
        // 数组后部分翻转
        reverse(nums, k, nums.length - 1);
    }

    /**
     * 数组翻转
     * @param nums
     * @param start
     * @param end
     */
    public static void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start += 1;
            end -= 1;
        }
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7};
        // 1 2 3 4 5 6 7
        // 7 1 2 3 4 5 6
        rotate(nums,3);
        System.out.println(Arrays.toString(nums));
    }
}
